package cn.safekeeper.guide.admin.service.impl;


import cn.safekeeper.guide.admin.constant.Constants;
import cn.safekeeper.guide.admin.constant.UserConstants;
import cn.safekeeper.guide.admin.domain.entity.RegisterBody;
import cn.safekeeper.guide.admin.domain.entity.SysUser;
import cn.safekeeper.guide.admin.service.ISysUserService;
import cn.safekeeper.guide.admin.utils.AsyncLogUtil;
import cn.safekeeper.guide.admin.utils.MessageUtils;
import cn.safekeeper.guide.admin.utils.ip.IpUtils;
import cn.safekeeper.guide.admin.utils.sign.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 注册校验方法
 */
@Component
public class SysRegisterService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private AsyncLogUtil asyncLogUtil;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody, HttpServletRequest request) {
        String msg = "", username = registerBody.getUsername();

        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        } else {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            sysUser.setNickName(username);
            sysUser.setPassword(Md5Utils.hash(registerBody.getPassword()));
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                asyncLogUtil.recordLoginInfoAsync(username, Constants.REGISTER, MessageUtils.message("user.register.success"),
                        IpUtils.getIpAddr(request), IpUtils.getOsName(request), IpUtils.getBrowserName(request));
            }
        }
        return msg;
    }
}
